package com.wn.icloud.plugin.util;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author kyy
 * @date 2019/04/13
 */
@Slf4j
public class JdlUtil {


    public static boolean genCodeFormJdl(Collection<File> files, long timeOut) {
        if (files == null || files.isEmpty()) {
            return false;
        }
        List<String> collect = files.stream().map(File::getAbsolutePath).collect(Collectors.toList());
        return genCodeFormJdlByFileNames(collect, timeOut);
    }

    public static boolean genCodeFormJdlByFileNames(List<String> fileNames, long timeOut) {
        if (fileNames == null || fileNames.size() == 0) {
            return false;
        }
        String cachePath = ".jhipster";
        try {
            FileUtils.deleteDirectory(new File(cachePath));
            return genCode2(fileNames, timeOut);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                FileUtils.deleteDirectory(new File(cachePath));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }

    private static boolean genCode1(List<String> fileNames) throws IOException, InterruptedException {
        boolean rs = false;
        String command = "C:\\Users\\zhinengsuo4\\AppData\\Roaming\\npm\\jhipster.cmd import-jdl " +
                fileNames.stream().collect(Collectors.joining(" "));
        log.info(command);
        Process process = Runtime.getRuntime().exec(command);
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(process.getInputStream()));
        int exitCode = process.waitFor();
        if (exitCode == 0) {
            log.info("success");
            rs = true;
        } else {
            log.error("\nExited with error code : " + exitCode);
            rs = false;
        }
        String line;
        while ((line = reader.readLine()) != null) {
            log.info(line);
        }
        return rs;
    }

    private static boolean genCode2(List<String> fileNames, long timeOut) throws IOException, InterruptedException {
        List<String> commands = Lists.newArrayList();
        commands.add(getJhipsterPath());
        commands.add("import-jdl");
        fileNames.forEach(commands::add);

        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.redirectErrorStream(true);
        boolean rs;
        Process process = processBuilder.start();
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(process.getInputStream()));
        try {
            process.waitFor(timeOut, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
        process.destroy();
        Thread.sleep(1000);
        if (process.exitValue() == 0) {
            log.info("success");
            rs = true;
        } else {
            log.error("\nExited with error code : " + process.exitValue());
            rs = false;
        }
        String line;
        while ((line = reader.readLine()) != null) {
            log.info(line);
        }

        return rs;
    }

    private static String getJhipsterPath() {
        String osName = System.getProperty("os.name");
        if (osName.contains("Windows")) {
            String userName = System.getProperty("user.name");
            return "C:\\Users\\" + userName + "\\AppData\\Roaming\\npm\\jhipster.cmd";
        } else {
            return "jhipster";
        }
    }

    public static void main(String[] args) throws IOException {
        System.out.println(System.getProperty("user.name"));
        System.out.println(System.getProperties());
        // genCodeFormJdlByFileNames(Arrays.asList("/Users/kyy/works/xd/code/2rd/digitalshop-backend-v2/jdl/user.jdl"));
    }

}
